package com.coocaa.typhoon.api.v1.userfile.util;

/**
 * @author bijiahao
 * @date : 2025/9/26 18:15
 * @description
 */
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.xslf.usermodel.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

public class Ppt2PicUtil {

    /**
     * pptx → 每页 PNG
     * @param pptFile  输入文件
     * @param outDir   输出目录（每页 1 张 PNG）
     * @param dpi      分辨率（300 约等于打印级别）
     */
    public static void convertPptxToPNG(File pptFile, File outDir, int dpi) throws IOException {
        if (!outDir.exists()) outDir.mkdirs();
        XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(pptFile));

        // 计算缩放（默认 72 dpi → 目标 dpi）
        double scale = dpi / 72.0;
        Dimension pgsize = ppt.getPageSize();
        int width = (int) (pgsize.width * scale);
        int height = (int) (pgsize.height * scale);

        List<XSLFSlide> slides = ppt.getSlides();
        for (int i = 0; i < slides.size(); i++) {
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = img.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setPaint(Color.WHITE);
            graphics.fill(new Rectangle2D.Float(0, 0, width, height));
            graphics.scale(scale, scale);

            slides.get(i).draw(graphics);   // 把幻灯片画进 BufferedImage
            graphics.dispose();


            Thumbnails.of(img)
                    .scale(1.0)              // 不缩放
                    .outputQuality( 0.85f)
                    .outputFormat("png")
                    .toFile(new File("/Users/bijiahao/test/out0928/" + i + ".png"));
            break;
//            File outFile = new File(outDir, String.format("page_%03d.png", i + 1));
//            ImageIO.write(img, "PNG", outFile);
        }
        ppt.close();
    }

    // 简单测试
    public static void main(String[] args) throws IOException {
        convertPptxToPNG(new File("/Users/bijiahao/Downloads/20250926_1971540257031720960.pptx"), new File("/Users/bijiahao/test/out1"), 150);
        System.out.println("转换完成！");
    }
}